﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;

using Ext.Net;
using ZP.Data;
using ZP.Service;
using Kwan.Helper.Bitmaps;
using Kwan.Data;

namespace ZP.Web.Admin.AD
{
    public partial class Default : UIPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                BtnAddClassInfo.Hidden = !permit[0];
                AppendChild.Hidden = !permit[0];
                BtnAddInfo.Hidden = !permit[0];
                Rename.Hidden = !permit[2];
                btnChangeHot.Hidden = !permit[2];

                BtnDeleteInfo.Hidden = !permit[3];
                Remove.Hidden = !permit[3];
                if (permit[3])
                {
                    List<GridCommand> gridCommand = new List<GridCommand>{
                        ExtHelper.CreateGridCommand("Delete", Icon.Delete, "删除", "删除该条记录")
                    };
                    GridPanel1.ColumnModel.Columns.Add(ExtHelper.CreateCommandColumn(gridCommand));
                    gridCommand.Clear();
                }

            }
        }

        protected void BtnAddInfo_Click(object sender, EventArgs e)
        {
            SetEditWindow(new VAD());
            EditWindow.Show();
        }

        [DirectMethod]
        public void DeleteSelected(string obj)
        {
            using (IConnectinContext cc = DBContext.Context1)
            {
                Expression exp = new Expression();
                string[] list = obj.Split(',');
                cc.BeginTransaction();
                for (int i = 0; i < list.Length - 1; ++i)
                {
                    exp = TAD.entityID == int.Parse(list[i]);
                    exp.Delete<TAD>();
                }
                cc.Commit();
            }
            Store1.DataBind();
        }

        [DirectMethod]
        public void ChangeState(string obj, string cmd)
        {
            IList<TAD> list = JSON.Deserialize<IList<TAD>>(obj);
            if (list.Count > 0)
            {
                foreach (TAD tt in list)
                {
                    string[] arr = cmd.Split(char.Parse("_"));
                    BaseHelper.SetPropertyValue(tt, arr[0], arr[1]);
                    this.EntityDAO.Save(tt);
                }
                using (CrudMgr<TAD, VAD, int> crud = new CrudMgr<TAD, VAD, int>())
                    crud.ChangeState(list, cmd);
                Store1.DataBind();
            }
            else
            {
                ExtHelper.GetNotification("系统提示", "请至少选择一项！").Show();
            }
        }

        [DirectMethod]
        public void EditInfo(string id)
        {
            using (CrudMgr<TAD, VAD, int> crud = new CrudMgr<TAD, VAD, int>())
                SetEditWindow(crud.ViewDAO.LoadById(id));
            EditWindow.Show();
        }

        protected void RefreshDS(object sender, StoreRefreshDataEventArgs e)
        {
            NameValueCollection ps = new NameValueCollection();
            ps.Set("gridsort", e.Sort);
            ps.Set("dir", e.Dir.ToString());
            
            //搜索项
            ps.Set("Cid", txtFilter.Text);
            ps.Set("Title", txtSearch.Text);

            using (CrudMgr<TAD, VAD, int> crud = new CrudMgr<TAD, VAD, int>())
            {
                crud.EntityDAO.QueryBuilder = new ADQuery();
                List<VAD> ListView = crud.LoadListData(ps, e.Start > 0 ? e.Start : 0, e.Limit);

                e.Total = Convert.ToInt32(crud.TotalCount(ps));
                Store1.DataSource = ListView;
                Store1.DataBind();
            }
        }

        protected void NewEditWindow()
        {
            txtID.Text = "0";
			txtEndDate.Text = string.Empty;
            txtHot.Checked = false;
			txtImage.Text = string.Empty;
			txtMemo.Text = string.Empty;
            txtEnable.Checked = true;
			txtStartDate.Text = string.Empty;
			txtTitle.Text = string.Empty;
			txtUrl.Text = string.Empty;
        }

        protected void SetEditWindow(VAD tt)
        {
            txtID.Text = tt.id.ToString();
            txtCid.SetValue(tt.Cid.ToString(), tt.ClassName);
			txtEndDate.Text = tt.EndDate.ToString();
            txtHot.Checked = tt.Hot;
			txtImage.Text = tt.Image;
			txtMemo.Text = tt.Memo;
            txtEnable.Checked = tt.Enable;
			txtStartDate.Text = tt.StartDate.ToString();
			txtTitle.Text = tt.Title;
			txtUrl.Text = tt.Url;
        }

        protected void SaveEditWindow(object sender, DirectEventArgs e)
        {
            using (CrudMgr<TAD, VAD, int> crud = new CrudMgr<TAD, VAD, int>())
            {
                TAD tt = Convert.ToInt32(txtID.Text) > 0 ? crud.EntityDAO.LoadById(txtID.Text) : new TAD();
                using (Cutter imgCutter = new Cutter())
                {
                    imgCutter.NoCut = true;
                    imgCutter.DefPath = "Upload\\AD";
                    imgCutter.PathArray = new string[] { "pAD" };
                    tt.Image = txtImage.FileContent.Length > 0 ?
                        imgCutter.UploadImage(txtImage.FileContent, string.Empty) : tt.Image;
                }
                tt.CreatedDate = DateTime.Now;
                tt.EndDate = DateTime.Parse(txtEndDate.Text);
                //tt.Height = txtHeight.Text;
                tt.Cid = Convert.ToInt32(txtCid.Value);
                tt.Hot = txtHot.Checked;
                tt.Memo = txtMemo.Text;
                tt.Enable = txtEnable.Checked;
                tt.StartDate = DateTime.Parse(txtStartDate.Text);
                tt.Title = txtTitle.Text;
                tt.Url = txtUrl.Text;

                crud.EntityDAO.Save(tt);
            }
            //string AdPath = Path.Combine(Server.MapPath("~/ul/Ad"), tt.id);
            //if (BitmapHelper.SaveBitmap(AdPath, Request.Files))

            Store1.DataBind();
            EditWindow.Hide();
        }

        [DirectMethod]
        public void InitClassInfo(string id)
        {
            TADClass tt = new TADClass();
            tt.Pid = Convert.ToInt32(id);
            SetClass(tt);
            ClassWindow.Show();
        }

        [DirectMethod]
        public void SetClassInfo(string id)
        {
            using (ClassMgr<TADClass> classMgr = new ClassMgr<TADClass>())
            {
                TADClass tt = classMgr.EntityDAO.LoadById(id);
                SetClass(tt);
            }
            ClassWindow.Show();
        }

        private void SetClass(TADClass tt)
        {
            txtClassID.Text = tt.id.ToString().ToString();
            txtClassNameCN.Text = tt.NameCN;
            txtClassNameEN.Text = tt.NameEN;
            txtClassPid.Text = tt.Pid.ToString();
            txtClassSort.Text = tt.Sort.ToString();
        }

        protected void SaveClassForm(object sender, EventArgs e)
        {
            string x = txtClassPid.Text;
            using (ClassMgr<TADClass> classMgr = new ClassMgr<TADClass>())
            {
                TADClass tt = Convert.ToInt32(txtClassID.Text) == 0 ? new TADClass() : classMgr.EntityDAO.LoadById(txtClassID.Text);
                tt.NameCN = txtClassNameCN.Text;
                tt.NameEN = txtClassNameEN.Text;
                tt.Pid = string.IsNullOrEmpty(txtClassPid.Text) ? 0 : int.Parse(txtClassPid.Text);
                tt.Sort = Convert.ToInt32(txtClassSort.Text);

                classMgr.EntityDAO.Save(tt);
            }
            ClassWindow.Hide();
            RefreshTree();
        }

        protected void GetExamplesNodes(object sender, NodeLoadEventArgs e)
        {
            if (e.NodeID == "root")
            {
                using (ClassMgr<TADClass> classMgr = new ClassMgr<TADClass>())
                {
                    List<TADClass> ClassList = classMgr.EntityDAO.Load(new NameValueCollection());
                    List<TADClass> Parent = ClassList.FindAll(delegate(TADClass tt) { return tt.Pid == 0; }); //父节点
                    e.Nodes = CreateTree(ClassList, Parent);
                }
            }
        }

        private TreeNodeCollection CreateTree(List<TADClass> list, List<TADClass> Parent)
        {
            TreeNodeCollection nodes = new TreeNodeCollection(false);
            foreach (TADClass t in Parent)
            {
                TreeNode node = new TreeNode();
                List<TADClass> child = list.FindAll(delegate(TADClass tt) { return tt.Pid == t.id; });
                if (child.Count > 0)
                {
                    node.NodeID = t.id.ToString();
                    node.Text = t.NameCN;
                    //node.SingleClickExpand = true;
                    node.Nodes.AddRange(CreateTree(list, child));
                }
                else
                {
                    node.NodeID = t.id.ToString();
                    node.Text = t.NameCN;
                    node.Leaf = true;
                    //node.SingleClickExpand = true;
                }
                nodes.Add(node);
            }
            return nodes;
        }

        protected void RemoteRename(object sender, RemoteRenameEventArgs e)
        {
            e.Accept = true;
            using (ClassMgr<TADClass> classMgr = new ClassMgr<TADClass>())
            {
                TADClass tt = classMgr.EntityDAO.LoadById(e.NodeID);
                tt.NameCN = e.NewText;
                classMgr.EntityDAO.Save(tt);
            }
        }

        protected void RemoteRemove(object sender, RemoteActionEventArgs e)
        {
            using (ClassMgr<TAD> crud = new ClassMgr<TAD>())
            {
                List<TAD> list = crud.EntityDAO.Load(" s.Cid = '" + e.NodeID + "'", new Dictionary<string, object>());
                if (list.Count > 0)
                {
                    X.Msg.Alert("系统提示", "不能删除有内容的类别！").Show();
                }
                else
                {
                    e.Accept = true;
                    using (ClassMgr<TADClass> classMgr = new ClassMgr<TADClass>())
                        classMgr.EntityDAO.DeleteById(e.NodeID);
                }
            }
        }

        protected void RemoteAppend(object sender, RemoteAppendEventArgs e)
        {
            e.Accept = true;
            TADClass tt = new TADClass();
            tt.NameCN = e.Text;
            tt.Pid = int.Parse(e.ParentNodeID);
            using (ClassMgr<TADClass> classMgr = new ClassMgr<TADClass>())
                classMgr.EntityDAO.Save(tt);
        }

        protected void RemoteMove(object sender, RemoteMoveEventArgs e)
        {
            e.Accept = true;
            using (ClassMgr<TADClass> classMgr = new ClassMgr<TADClass>())
            {
                TADClass tt = classMgr.EntityDAO.LoadById(e.NodeID);
                tt.Pid = int.Parse(e.TargetNodeID);
                classMgr.EntityDAO.Save(tt);
            }
            
        }
        [DirectMethod]
        public void RefreshTree()
        {
            txtFilter.Text = "";
            ClassTree.ReloadAsyncNode("root", new JFunction());
            ClassTree.ExpandAll();
            EWTree.ReloadAsyncNode("root", new JFunction());
            EWTree.ExpandAll();
        }
    }
}